#include <QDebug>
#include <QMessageBox>
#include "input.h"
#include "ui_input.h"
#include "mainwindow.h"

Input::Input(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Input)
{
    ui->setupUi(this);

    this->is_answer_show = false;
    this->ui->answer_text_edit->setVisible(this->is_answer_show);
    this->main = nullptr;
}

Input::~Input()
{
    delete ui;
}

void Input::showEvent(QShowEvent *) {
    this->db = QSqlDatabase::addDatabase("QSQLITE");
    this->db.setDatabaseName("textbook.db");
    if (!this->db.open()) {
        QString err_str = this->db.lastError().databaseText();
        QMessageBox::critical(this, "系统错误", "打不开数据库文件，错误信息：" + err_str);
        exit(0);
        return;
    }

    QString id = QVariant(this->current_id).toString();
    QSqlQuery q;
    if (this->current_type == 0) {
        q = this->db.exec("SELECT `node_name`, `content` FROM `node` WHERE `article_id` = " + id +
                          " ORDER BY RANDOM() LIMIT 1");
    } else if (this->current_type == 1) {
        q = this->db.exec("SELECT `node_name`, `content` FROM `node` WHERE `parent_node_id` = " + id +
                          " ORDER BY RANDOM() LIMIT 1");
    }
    if (q.next()) {
        this->ui->tip_line_edit->setText(q.value("node_name").toString());
        this->ui->answer_text_edit->setPlainText(q.value("content").toString());
    }
}

void Input::on_toggle_answer_button_clicked()
{
    this->is_answer_show = !this->is_answer_show;
    this->ui->answer_text_edit->setVisible(this->is_answer_show);
}

void Input::on_input_text_edit_textChanged()
{
    if (this->ui->input_text_edit->toPlainText() == this->ui->answer_text_edit->toPlainText()) {
        QString id = QVariant(this->current_id).toString();
        QSqlQuery q;
        if (this->current_type == 0) {
            q = this->db.exec("SELECT `node_name`, `content` FROM `node` WHERE `article_id` = " + id +
                              " ORDER BY RANDOM() LIMIT 1");
        } else if (this->current_type == 1) {
            q = this->db.exec("SELECT `node_name`, `content` FROM `node` WHERE `parent_node_id` = " + id +
                              " ORDER BY RANDOM() LIMIT 1");
        }
        if (q.next()) {
            this->ui->input_text_edit->setPlainText("");
            this->ui->tip_line_edit->setText(q.value("node_name").toString());
            this->ui->answer_text_edit->setPlainText(q.value("content").toString());
        }
    }
}

void Input::on_return_button_clicked()
{
    this->db.close();
    QSqlDatabase::removeDatabase(this->db.databaseName());
    ((MainWindow*)this->main)->show();
    this->close();
}
